# !/usr/bin/env python
# -*- coding: utf-8 -*-

import uvicorn

from fastapi import FastAPI

from starlette.exceptions import HTTPException
from starlette.middleware.cors import CORSMiddleware
from starlette.status import HTTP_422_UNPROCESSABLE_ENTITY

from app.db.db_utils import startup, shutdown
from app.core.errors import http_422_error_handler, http_error_handler
from app.core.config import ALLOWED_HOSTS, PROJECT_NAME, API_V1_STR
# from app.api_v1.law_enforcement.api_v1.api_v1 import router as punishment_api_v1_router
from app.middleware.IP_firewall import IPFirewallMiddleware, RequestLogMiddleware
from app.middleware.limiter import LimiterMiddleware


from app.api_v1.router import api_router


app = FastAPI(title=PROJECT_NAME)

if not ALLOWED_HOSTS:
    ALLOWED_HOSTS = ["*"]

app.add_middleware(
    CORSMiddleware,
    allow_origins=ALLOWED_HOSTS,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 请求日志记录中间件
app.add_middleware(RequestLogMiddleware)
# ip 白名单中间件
# app.add_middleware(IPFirewallMiddleware)
# API访问速度限制中间件
app.add_middleware(LimiterMiddleware)

# 项目启动时，连接数据库
app.add_event_handler("startup", startup)
# 关闭时，关闭数据库连接
app.add_event_handler("shutdown", shutdown)

# 错误处理
app.add_exception_handler(HTTPException, http_error_handler)
app.add_exception_handler(HTTP_422_UNPROCESSABLE_ENTITY, http_422_error_handler)

# 行政处罚API
app.include_router(api_router, prefix=API_V1_STR)

if __name__ == '__main__':
    uvicorn.run(app, host='0.0.0.0', port=8000, reload=True)
